package cn.kgc.service.impl;

import cn.kgc.entity.Users;
import cn.kgc.excpetion.GraceException;
import cn.kgc.feign.ResumeFeignClient;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.mapper.UsersMapper;
import cn.kgc.service.UserTccService;
import cn.kgc.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * @author YC
 */
@Slf4j
@Service("usersService")
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private ResumeFeignClient resumeFeignClient;
    @Resource
    private UserTccService userTccService;

    @Override
    public Users login(String phoneNum) {
        // 根据手机号查询用户，不为空直接返回，为空则创建一个带有默认属性的实例返回并保存
        return this.getOne(new LambdaQueryWrapper<Users>().eq(Users::getMobile, phoneNum));
    }

    /**
     * 注册用户时同时调用初始化简历远程服务
     *
     * @param phoneNum 手机号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional
    public Users registerAndInitResume(String phoneNum) {
        Users user = userTccService.tryRegisterUser(null, phoneNum);
        // 调用远程接口初始化简历
        GraceJSONResult result = resumeFeignClient.initResume(user.getId());
        if (!((boolean) result.getData())) {
            GraceException.display(ResponseStatusEnum.RESUME_INIT_ERROR);
        }
        return user;
    }

}
